//
//  StoreBaseViewController.m
//  ebook
//
//  Created by 吴超飞 on 16/3/28.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "StoreBaseViewController.h"
#import "PushWebviewViewController.h"
#import "UIImageView+WebCache.h"
#import "StoreMenuView.h"
#import "GuestLoginManager.h"
#import "DownloadManager.h"
#import "EbookNetRequest.h"
#import "WebViewController.h"
#import "MISAlertController.h"
#import "ChapterListViewController.h"

#define MIMINTERVAL 1

@interface StoreBaseViewController ()<UIGestureRecognizerDelegate>{
    
    BOOL isExcuting;
    NSInteger timeInteval;
    NSTimer *countDownTimer;
    BOOL isLoadingNull;//标识当前是否正在加载无内容的页面，以便只是是否提示加载框，UIWebview使用
    NSTimeInterval initTime;//页面初始化的时间，广告弹出的时间跟该时间的间隔如果小于MIMINTERVAL则不响应，以防止广告自动弹出
}

@property (nonatomic, retain) UIView *coverView;
@property (nonatomic, assign) BOOL hasAutoLogin;//提示未登录时，先做一次自动登录，只有在自动登录失败时才提示登录框
@property (strong, nonatomic) UIProgressView *progressView;

@end

@implementation StoreBaseViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    if (!self.isNetConnect) {
        [self.view addSubview:self.coverView];
    }
    
    initTime = [[NSDate date]timeIntervalSince1970];
    
    // 进度条
    if(iOS8){
        UIProgressView *progressView = [self createProgressView];
        [self.webView8 addSubview:progressView];
        self.progressView = progressView;
        [self.webView8 addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground) name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    
//    if(iOS8){
        if (!_bridge8)
            _bridge8 = [WKWebViewJavascriptBridge bridgeForWebView:_webView8 webViewDelegate:self handler:self.messageHandler];
//    }else{
//        if (!_bridge7)
//            _bridge7 = [WebViewJavascriptBridge bridgeForWebView:_webView7 webViewDelegate:self handler:self.messageHandler];
//    }
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    //开启iOS7的滑动返回效果
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        //只有在二级页面生效
        if ([self.navigationController.viewControllers count] == 2) {
            self.navigationController.interactivePopGestureRecognizer.delegate = self;
        }
    }
    
//    //离开时释放webview
//    _webView7 = nil;
//    _webView7.delegate = nil;
//    [_webView7 stopLoading];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    //代理置空，否则会闪退
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    
//    if(iOS8)
        [self webView:_webView8 didFinishNavigation:nil];
//    else
//        [self webViewDidFinishLoad:_webView7];
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    return YES;
}

-(WVJBHandler)messageHandler{
    
    __unsafe_unretained typeof(self) weakSelf = self;
    if (!_messageHandler) {
        _messageHandler = ^(id data, WVJBResponseCallback responseCallback) {
            
            __strong __typeof(self) strongSelf = weakSelf;
            MTLog(@"ObjC received message from JS: %@", data);
            
            NSDictionary *dict = [NSDictionary dictionaryWithDictionary:[strongSelf dictionaryWithJsonString:data]];
            NSString *act = @"read";
            if([[dict allKeys] containsObject:@"act"])
                act = [dict objectForKey:@"act"];
            
            if([act isEqualToString:@"read"]){//按指定章节阅读｜｜开始阅读（开始阅读等同于从书架阅读，需判断上次阅读位置）
                Book *book = [[Book alloc]init];
                if([[dict allKeys] containsObject:@"aid"])
                    book.bookid = [dict objectForKey:@"aid"];
                if([[dict allKeys] containsObject:@"cid"])
                    book.firstchapterid = [dict objectForKey:@"cid"];
                if([[dict allKeys] containsObject:@"cname"])
                    book.firstchaptername = [dict objectForKey:@"cname"];
                if([[dict allKeys] containsObject:@"lastupdate"])
                    book.updatetime = [dict objectForKey:@"lastupdate"];
                if([[dict allKeys] containsObject:@"siteid"])
                    book.siteid = [dict objectForKey:@"siteid"];
                [strongSelf pushToReader:book isMiddleIn:[[dict objectForKey:@"checkcase"] intValue]==0];
                
            }else if([act isEqualToString:@"info"]){
                NSString *aname,*url;
                BOOL isSelf = NO;
                if([[dict allKeys] containsObject:@"aname"])
                    aname = [dict objectForKey:@"aname"];
                if([[dict allKeys] containsObject:@"url"])
                    url = [dict objectForKey:@"url"];
                if([[dict allKeys] containsObject:@"self"])
                    isSelf = [[dict objectForKey:@"self"] intValue]==1;
                
                if(!isSelf)
                    [strongSelf pushAWebview:url title:aname];
                else
                    [strongSelf loadNewUrl:url title:aname];
                
            }else if([act isEqualToString:@"login"]){
                
                [strongSelf presentLogin];
            }else if([act isEqualToString:@"shareMenu"]){
                
                [strongSelf shareWithDict:dict];
            }else if([act isEqualToString:@"redirectMenu"]){//{"act":"redirectMenu", "index":"1"}
                
                [strongSelf redirectMenu:[[dict objectForKey:@"index"] integerValue]];
            }else if([act isEqualToString:@"addBookcase"]){//加入书架{"act":"addBookcase", "aid":"7554"}
                [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateBookshelfNotification object:[dict objectForKey:@"aid"]];
            }else if([act isEqualToString:@"delBookcase"]){//移除书架{"act":"delBookcase", "aid":"7554"}
                [[NSNotificationCenter defaultCenter] postNotificationName:kDelShouldUpdateBookshelfNotification object:[dict objectForKey:@"aid"]];
            }else if([act isEqualToString:@"readChapterList"]){
                
                Book *book = [[Book alloc]init];
                if([[dict allKeys] containsObject:@"aid"])
                    book.bookid = [dict objectForKey:@"aid"];
                if([[dict allKeys] containsObject:@"name"])
                    book.firstchaptername = [dict objectForKey:@"name"];
                if([[dict allKeys] containsObject:@"siteid"])
                    book.siteid = [dict objectForKey:@"siteid"];
                
                ChapterListViewController *pushVc = [[ChapterListViewController alloc] initWithBook:book];
                [strongSelf.navigationController pushViewController:pushVc animated:YES];
                
            }else if([act isEqualToString:@"download"]){
                Book *book = [[Book alloc]init];
                if([[dict allKeys] containsObject:@"aid"])
                    book.bookid = [dict objectForKey:@"aid"];
                if([[dict allKeys] containsObject:@"bookname"])
                    book.bookname = [dict objectForKey:@"bookname"];
                if([[dict allKeys] containsObject:@"lastupdate"])
                    book.updatetime = [dict objectForKey:@"lastupdate"];
                if([[dict allKeys] containsObject:@"siteid"])
                    book.siteid = [dict objectForKey:@"siteid"];
                [strongSelf wholeDownload:book];
            }else if([act isEqualToString:@"openulr"]){
                NSString *urlStr = nil;
                if([[dict allKeys] containsObject:@"url"])
                    urlStr = [dict objectForKey:@"url"];
                if (urlStr.length>0&&![urlStr hasPrefix:@"http"]) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
                }
            }else{
                responseCallback(@"0");
            }
        };
    }
    
    return _messageHandler;
}

-(void)shareWithDict:(NSDictionary *)dict{
    
    //{"act":"shareMenu","imgurl":"","url":"","intro":"","title":""}
    NSString *intro = dict[@"intro"];
    NSString *text = intro.length>120?[intro substringToIndex:120]:intro;
    UIImageView *imageV = [[UIImageView alloc] init];
    UIView *shareView = nil;
    if (isIpad) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(MTScreenW/8*7-50, MTScreenH/4+30, 10, 10);
        [self.view addSubview:btn];
        
        shareView = btn;
    }
    if (!dict[@"imgurl"]) {
        imageV.image = [UIImage imageNamed:@"share"];
        [super sharewithview:shareView text:text dic:dict imagesArray:@[imageV.image]];
    } else {
        [imageV sd_setImageWithURL:[NSURL URLWithString:dict[@"imgurl"]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [super sharewithview:shareView text:text dic:dict imagesArray:@[image?image:[UIImage imageNamed:@"share"]]];
        }];
    }
}

-(void)webView:(UIView *)webview loadUrl:(NSString *)url{
    
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:kToken];
    NSRange range = [url rangeOfString:@"?token="];
    if(range.length==7)
        url = [url substringToIndex:range.location];
    BOOL containQuestionMark = [url rangeOfString:@"?"].length>0;
    if(token)url = [NSString stringWithFormat:@"%@%@token=%@&wifi=%d",url,containQuestionMark?@"&":@"?",token,[CoreStatus isWifiEnable]];
    MTLog(@"url:%@",url);
    
//    if(iOS8)
        [(WKWebView*)webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
//    else
//        [(UIWebView*)webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60]];
}

-(void)beginTimer{
    
    timeInteval = 40;
    if(!countDownTimer)
        countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
    else
        [countDownTimer fire];
}

-(void)timeFireMethod{
    
    timeInteval--;
    if(timeInteval<=0){
        [countDownTimer invalidate];
        countDownTimer = nil;
        
        if(self.HUD.superview){//只有当指示框在的时候才执行
            
            [self hideHUD];
            [self showFailView];
        }
    }
}

-(void)redirectMenu:(NSInteger)index{
    
}

-(void)presentLogin{
    
    __unsafe_unretained typeof(self) weakSelf = self;
    
    if(self.hasAutoLogin){
        MTLoginViewController *loginVc = [[MTLoginViewController alloc] init];
        loginVc.delegate = self;
        loginVc.lastController = self;
        [self.navigationController pushViewController:loginVc animated:YES];
    }else{
        [GuestLoginManager autoLogin:^(BOOL issuc) {
            __strong __typeof(self) strongSelf = weakSelf;
            strongSelf.hasAutoLogin = YES;
            if(issuc)[strongSelf webView:strongSelf.webView loadUrl:_url];
        }];
    }
}

#pragma mark - 前后台切换
//应用切换到后台
- (void)applicationEnterBackground{
    [[NSUserDefaults standardUserDefaults] setDouble:[[NSDate date] timeIntervalSince1970] forKey:kLastReloadBookstoreTime];
    if(_url)
        [[NSUserDefaults standardUserDefaults] setObject:_url forKey:kLastWebviewUrl];
}

//应用切换到前台
-(void)applicationWillEnterForeground{
    double interval = [[NSDate date] timeIntervalSince1970]-[[NSUserDefaults standardUserDefaults] doubleForKey:kLastReloadBookstoreTime];
    if (interval > 20*60) {// 60*60
        [self enterForegroundReloadWebview];
    }
}

//刷新webview
-(void)enterForegroundReloadWebview{
    
    _url = [[NSUserDefaults standardUserDefaults] objectForKey:kLastWebviewUrl];
    [self reloadUrl];
}

#pragma mark - LoginDelegate
-(void)loginSuccess{
    
    NSString *location = _webView8.URL.absoluteString;
    [self webView:self.webView loadUrl:location];
}

-(void)loginCancel{
    
}

-(UIView *)webView{
    
//    if(!_webView){
//        _webView = iOS8?self.webView8:self.webView7;
//    }
    
    return self.webView8;
}

-(WKWebView *)webView8{
    
    if(!_webView8){
        
        _webView8 = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, MTScreenW, MTScreenH - SafeAreaBTabbarHeight-SafeAreaTopHeight)];
        _webView8.backgroundColor = [UIColor whiteColor];
        _webView8.navigationDelegate = self;
        _webView8.scrollView.bounces = NO;
        _webView8.UIDelegate = self;
    }
    
    return _webView8;
}

//-(UIWebView *)webView7{
//
//    if(!_webView7){
//        _webView7 = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, MTScreenW, MTScreenH - 49-SafeAreaTopHeight)];
//        _webView7.backgroundColor = [UIColor whiteColor];
//        _webView7.delegate = self;
//        _webView7.scalesPageToFit = YES;
//        _webView7.scrollView.bounces = NO;
//    }
//
//    return _webView7;
//}

//构建进度条
-(UIProgressView *)createProgressView{
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0.1, self.view.frame.size.width, 0)];
    progressView.tintColor = MTConfigColor(@"MTNavigationBar_background_Color");
    progressView.trackTintColor = [UIColor whiteColor];
    return progressView;
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        MTLog(@"网页传递的数据格式有误，json解析失败：%@",err);
        return nil;
    }
    
    return dic;
}

//push出一个webview的视图
- (void)pushAWebview:(NSString *)url title:(NSString *)title{
    
    //    url = @"http://192.168.0.113/chapterlist.php?aid=1&page=1#";
    PushWebviewViewController *pushVc = [[PushWebviewViewController alloc] initWithUrl:url title:title];
    [self.navigationController pushViewController:pushVc animated:YES];
}

- (void)loadNewUrl:(NSString *)url title:(NSString *)title{
    
    self.title = title;
    self.url = url;
    [self webView:self.webView loadUrl:url];
}

- (void)pushToReader:(Book *)book isMiddleIn:(BOOL)ismid{
    
    if(!book)return;
    if(isExcuting)return;
    isExcuting = YES;
    
    ReaderBookModel *readerbookModel = [[ReaderBookModel alloc] initWithBook:book isMiddleIn:ismid];
    [self.view addSubview:self.HUD];
    [self.view bringSubviewToFront:self.HUD];
    [self.HUD show:YES];
    double time = 0;
    if(![readerbookModel isExistCurrentChapter]){
        self.HUD.labelText = kInfoNetLoad;
        time = [[NSDate date] timeIntervalSince1970];
    }else{
        self.HUD.labelText = kInfoLocalLoad;
    }
    
    [readerbookModel getInitPageDataComplete:^(NSDictionary *dict,TurnResult result) {
        
        NSArray *array = [dict objectForKey:@"data"];
        if(!dict||!array||[array count]==0||result==TurnNoNet){//未获取到内容
            [ToastView showMsg:kContentErrorNoNetInfo inView:self.view isCenter:YES];
            [self.HUD removeFromSuperview];
            return ;
        }
        
        double inteval = 0.0f;
        if(time>0)inteval = 2.0 - ([[NSDate date] timeIntervalSince1970]-time);
        inteval = inteval<0?0:inteval;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, inteval * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
            [self.HUD removeFromSuperview];
            ReaderViewController *reader = [[ReaderViewController alloc] init];
            reader.readerBookModel = readerbookModel;
            [reader loadPageviewDatasource:dict];
            
            [self.navigationController pushViewController:reader animated:YES];
            isExcuting = NO;
        });
    }];
}

-(void)wholeDownload:(Book *)book{
    
    //对于需要全本缓存的书，先将书添加到书架
    [BookcaseOprationController addBookcase:book.bookid success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateBookshelfNotification object:book.bookid];
        MTLog(@"点击全本缓存，添加书架成功");
        
        //全本下载时不需要获取章节列表，章节列表直接存在压缩包里
        DownloadModel *download = [[DownloadModel alloc] init];
        download.book = book;
        download.chapter = nil;
        download.chapterList = nil;
        download.downloadType = Download_all;
        [[DownloadManager shareInstance] addDownload:download];//开始下载
    } failed:^(int stateCode, NSString *failMsg) {
       
        MTLog(@"点击全本缓存，添加书架失败");
        MISAlertController *alertController = [MISAlertController alertControllerWithTitle:@"缓存失败" message:failMsg preferredStyle:UIAlertControllerStyleAlert];
        MISAlertAction *okAction = [MISAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:okAction];
        [alertController showInViewController:self animated:YES];
    }];
}

-(MBProgressHUD *)HUD{
    if (!_HUD) {
        _HUD = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
        _HUD.center = self.view.center;
    }
    return _HUD;
}

- (void)showHUD{
//    if(!iOS8){
        [self.view addSubview:self.HUD];
        [self.view bringSubviewToFront:self.HUD];
        [self.HUD show:YES];
//    }
}

-(void)hideHUD{
//    if(!iOS8)
        [self.HUD removeFromSuperview];
}

- (void)reloadUrl{
    
    [self showHUD];
    [self webView:self.webView loadUrl:_url];
    [self hiddenFailView];
}

// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.webView8 && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            self.progressView.hidden = YES;
            [self.progressView setProgress:0 animated:NO];
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}

// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    NSTimeInterval navTime = [[NSDate date]timeIntervalSince1970];
//    MTLog(@"web请求跳转的时间差为:%f",navTime-initTime);
    BOOL isAllow = (navTime-initTime) > MIMINTERVAL;//防止广告自动弹出
    
    NSURLRequest *request = navigationAction.request;
    NSString *hostname = request.URL.host.lowercaseString;
    NSString *currenturl = webView.URL.host.lowercaseString;
    
    if (navigationAction.targetFrame == nil || navigationAction.navigationType==0){
        
        WebViewController *webv = [[WebViewController alloc] init];
        webv.isDirectLoadReques = YES;//[request.HTTPMethod isEqualToString:@"POST"];
        webv.request = navigationAction.request;
        
        if(isAllow)[self.navigationController pushViewController:webv animated:YES];
        decisionHandler(WKNavigationActionPolicyCancel);
    }else if(navigationAction.navigationType == -1
             && hostname && currenturl && ![hostname isEqualToString:currenturl]){
    
        BOOL isIgnore = NO;
        NSArray *adighost = kBookCityDataDict[@"adighost"];
        for(NSString *host in adighost){
            if ([hostname rangeOfString:host].length>0) {
                isIgnore = YES;
            }
        }
        
        if(isAllow&&!isIgnore&&[navigationAction.request.URL.absoluteString hasPrefix:@"http"])[[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        decisionHandler(WKNavigationActionPolicyCancel);
    }else{
        
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

#pragma mark - WKNavigationDelegate 进度及错误提示 iOS8后使用
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    if(!isLoadingNull){
        [self showHUD];
        [self beginTimer];
    }
    if([CoreStatus currentNetWorkStatus] == CoreNetWorkStatusNone)
        [self showFailView];
}

-(void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    
    [self hideHUD];
    [self hiddenFailView];
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"]; //UIWebView内存占用过高、崩溃、内存溢出
    
    [countDownTimer invalidate];
    countDownTimer = nil;
}

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    
    [self hideHUD];
    [self hiddenFailView];
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"]; //UIWebView内存占用过高、崩溃、内存溢出
    
    [countDownTimer invalidate];
    countDownTimer = nil;
}

/// message: 收到的脚本信息.
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    MTLog(@"userContentController message:%@",message);
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"OK"
                                                        style:UIAlertActionStyleCancel
                                                      handler:^(UIAlertAction *action) {
                                                          completionHandler();
                                                      }]];
    [self presentViewController:alertController animated:YES completion:^{}];
}

//#pragma mark - UIWebViewDelegate 进度及错误提示 iOS7中使用
//-(void)webViewDidStartLoad:(UIWebView *)webView
//{
//    if(!isLoadingNull){
//        [self showHUD];
//        [self beginTimer];
//    }
//}
//
//-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
//{
//    if(error.code == -1009)
//        [self showFailView];
//}
//
//-(void)webViewDidFinishLoad:(UIWebView *)webView
//{
//    [self hideHUD];
//    [self hiddenFailView];
//    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"]; //UIWebView内存占用过高、崩溃、内存溢出
//
//    [countDownTimer invalidate];
//    countDownTimer = nil;
//}
//
//- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//
//    isLoadingNull = NO;
//    if (navigationType == UIWebViewNavigationTypeFormSubmitted||navigationType ==UIWebViewNavigationTypeLinkClicked)
//    {
//        if([self isBlankLink:webView HttpRequest:request]){//所要跳转的地址是_blank标记的超连接
//            WebViewController *webv = [[WebViewController alloc] init];
//            webv.isDirectLoadReques = YES;//[request.HTTPMethod isEqualToString:@"POST"];
//            webv.url = request.URL.absoluteString;
//            webv.request = request;
//            [self.navigationController pushViewController:webv animated:YES];
//            return false;
//        }
//    }
//
//    return true;
//}

// 判断是否带_blank标记超连接
-(BOOL) isBlankLink:(UIWebView*) webView HttpRequest:(NSURLRequest*) request
{
    if(webView == nil || request == nil)
    {
        return NO;
    }
    
    NSURL* URL = [request URL];
    NSString* URLString = [URL absoluteString];
    
    int aLen = [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName(\"a\").length"] intValue];
    for (int n = 0; n < aLen; n ++)
    {
        NSString* html = [NSString stringWithFormat:@"document.getElementsByTagName(\"a\")[%d].href", n];
        // 获取href
        NSString* href = [webView stringByEvaluatingJavaScriptFromString:html];
        if ([URLString isEqualToString:href])
        {
            html = [NSString stringWithFormat:@"document.getElementsByTagName(\"a\")[%d].target", n];
            NSString* target = [webView stringByEvaluatingJavaScriptFromString:html];
            if([target isEqualToString:@"_blank"])
            {
                return YES;
            }else{
                break;
            }
        }
    }
    return NO;
}

#pragma mark - FailView
- (void)showFailView
{
    [self hideHUD];
    [self.view addSubview:self.coverView];
    [self.view bringSubviewToFront:self.coverView];
}

- (void)hiddenFailView
{
    if (!self.isNetConnect) {//网络没有连接
        
    } else {//网络有连接
        [_coverView removeFromSuperview];
        _coverView = nil;
    }
}

-(UIView *)coverView
{
    if (!_coverView) {
        
        _coverView = [[UIView alloc] init];
        _coverView.frame = CGRectMake(0, 0, MTScreenW, MTScreenH-SafeAreaTopHeight);
        _coverView.backgroundColor = MTConfigColor(@"MTBookCity_CoverViewBg_Color");//使用图片一样的背景色
        
        UIImage *image = [UIImage imageNamed:@"loadFail"];
        UIImageView *icon = [[UIImageView alloc] init];
        icon.frame = CGRectMake((MTScreenW-208)/2, 40, 208, 256);
        icon.image = image;
        icon.userInteractionEnabled = YES;
        [_coverView addSubview:icon];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.frame = CGRectMake(0, CGRectGetMaxY(icon.frame), MTScreenW, 80);
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.text = @"连接失败，请检查网络连接\n点击屏幕重试";
        titleLabel.numberOfLines = 2;
        
        titleLabel.font = [UIFont systemFontOfSize:16.0];
        titleLabel.textColor = MTConfigColor(@"MTBookCity_titleLabelText_Color");
        [_coverView addSubview:titleLabel];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(reloadView)];
        [self.view addGestureRecognizer:tap];
    }
    
    return _coverView;
}

- (void)reloadView
{
    [self reloadUrl];
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
//    if(iOS8){
        [_webView8 removeObserver:self forKeyPath:@"estimatedProgress"];
//    }
}

@end


